package com.vegetable.modules.controller.stock;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vegetable.common.utils.R;
import com.vegetable.modules.controller.AbstractController;
import com.vegetable.modules.entity.stock.SalesOutChangeRecord;
import com.vegetable.modules.entity.stock.po.SalesOutChangeRecordQueryPO;
import com.vegetable.modules.service.stock.ISalesOutChangeRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 销售出库变更记录 前端控制器
 * </p>
 *
 * @author system
 * @since 2025-10-23
 */
@Slf4j
@RestController
@RequestMapping("/salesout/changerecord")
@Api(tags = "销售出库变更记录管理")
public class SalesOutChangeRecordController extends AbstractController {

    @Autowired
    private ISalesOutChangeRecordService changeRecordService;

    /**
     * 分页查询销售出库变更记录列表
     *
     * @param po 查询参数
     * @return 分页数据
     */
    @GetMapping("/page")
    @ApiOperation(value = "分页查询变更记录", notes = "支持按销售出库单ID、单据编号、操作类型、变更类型、客户等条件分页查询")
    public R page(SalesOutChangeRecordQueryPO po) {
        log.info("分页查询销售出库变更记录，参数: {}", po);
        
        QueryWrapper<SalesOutChangeRecord> wrapper = new QueryWrapper<>();
        
        // 销售出库单ID
        if (po.getSalesOutId() != null) {
            wrapper.eq("sales_out_id", po.getSalesOutId());
        }
        
        // 单据编号（模糊查询）
        if (StringUtils.isNotBlank(po.getDocNo())) {
            wrapper.like("doc_no", po.getDocNo());
        }
        
        // 操作类型
        if (StringUtils.isNotBlank(po.getOperationType())) {
            wrapper.eq("operation_type", po.getOperationType());
        }
        
        // 变更类型
        if (StringUtils.isNotBlank(po.getChangeType())) {
            wrapper.eq("change_type", po.getChangeType());
        }
        
        // 客户ID
        if (po.getCustomerId() != null) {
            wrapper.eq("customer_id", po.getCustomerId());
        }
        
        // 客户名称（模糊查询）
        if (StringUtils.isNotBlank(po.getCustomerName())) {
            wrapper.like("customer_name", po.getCustomerName());
        }
        
        // 操作人姓名（模糊查询）
        if (StringUtils.isNotBlank(po.getOperatorName())) {
            wrapper.like("operator_name", po.getOperatorName());
        }
        
        // 操作时间范围
        if (po.getStartTime() != null) {
            wrapper.ge("operate_time", po.getStartTime());
        }
        if (po.getEndTime() != null) {
            wrapper.le("operate_time", po.getEndTime());
        }
        
        // 排序
        if (StringUtils.isNotBlank(po.getOrderBy())) {
            if ("asc".equalsIgnoreCase(po.getOrderSort())) {
                wrapper.orderByAsc(po.getOrderBy());
            } else {
                wrapper.orderByDesc(po.getOrderBy());
            }
        } else {
            // 默认按操作时间倒序
            wrapper.orderByDesc("operate_time");
        }
        
        // 分页查询
        IPage<SalesOutChangeRecord> page = changeRecordService.page(
            new Page<>(po.getPageCurrent(), po.getPageSize()), 
            wrapper
        );
        
        log.info("查询到 {} 条记录", page.getTotal());
        return R.data(page);
    }

    /**
     * 查询指定销售出库单的所有变更记录
     *
     * @param salesOutId 销售出库单ID
     * @return 变更记录列表
     */
    @GetMapping("/listBySalesOut/{salesOutId}")
    @ApiOperation(value = "查询指定销售出库单的变更记录", notes = "返回该销售出库单的所有变更记录，按操作时间倒序")
    public R listBySalesOut(
            @ApiParam(value = "销售出库单ID", required = true) 
            @PathVariable Long salesOutId) {
        log.info("查询销售出库单的变更记录，salesOutId: {}", salesOutId);
        
        QueryWrapper<SalesOutChangeRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("sales_out_id", salesOutId);
        wrapper.orderByDesc("operate_time");
        
        List<SalesOutChangeRecord> records = changeRecordService.list(wrapper);
        
        log.info("找到 {} 条变更记录", records.size());
        return R.data(records);
    }

    /**
     * 查询变更记录详情
     *
     * @param id 变更记录ID
     * @return 变更记录详情
     */
    @GetMapping("/detail/{id}")
    @ApiOperation(value = "查询变更记录详情", notes = "根据ID查询单条变更记录的详细信息")
    public R detail(
            @ApiParam(value = "变更记录ID", required = true) 
            @PathVariable Long id) {
        log.info("查询变更记录详情，id: {}", id);
        
        SalesOutChangeRecord record = changeRecordService.getById(id);
        
        if (record == null) {
            return R.fail("变更记录不存在");
        }
        
        return R.data(record);
    }

    /**
     * 统计变更次数
     *
     * @param salesOutId 销售出库单ID
     * @return 统计信息
     */
    @GetMapping("/statistics/{salesOutId}")
    @ApiOperation(value = "统计变更次数", notes = "统计指定销售出库单的商品明细和费用的变更次数")
    public R statistics(
            @ApiParam(value = "销售出库单ID", required = true) 
            @PathVariable Long salesOutId) {
        log.info("统计销售出库单变更次数，salesOutId: {}", salesOutId);
        
        QueryWrapper<SalesOutChangeRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("sales_out_id", salesOutId);
        
        // 统计商品明细变更次数
        QueryWrapper<SalesOutChangeRecord> commodityWrapper = wrapper.clone();
        commodityWrapper.eq("change_type", "COMMODITY");
        long commodityChangeCount = changeRecordService.count(commodityWrapper);
        
        // 统计费用变更次数
        QueryWrapper<SalesOutChangeRecord> costWrapper = wrapper.clone();
        costWrapper.eq("change_type", "COST");
        long costChangeCount = changeRecordService.count(costWrapper);
        
        // 统计综合变更次数
        QueryWrapper<SalesOutChangeRecord> combinedWrapper = wrapper.clone();
        combinedWrapper.eq("change_type", "COMBINED");
        long combinedChangeCount = changeRecordService.count(combinedWrapper);
        
        // 统计总变更次数
        long totalChangeCount = changeRecordService.count(wrapper);
        
        // 构建返回结果
        return R.data(new java.util.HashMap<String, Object>() {{
            put("salesOutId", salesOutId);
            put("commodityChangeCount", commodityChangeCount);
            put("costChangeCount", costChangeCount);
            put("combinedChangeCount", combinedChangeCount);
            put("totalChangeCount", totalChangeCount);
        }});
    }

    /**
     * 查询最近的变更记录
     *
     * @param limit 返回记录数，默认10条
     * @return 最近的变更记录列表
     */
    @GetMapping("/recent")
    @ApiOperation(value = "查询最近的变更记录", notes = "查询系统中最近的变更记录，用于概览展示")
    public R recent(
            @ApiParam(value = "返回记录数", defaultValue = "10") 
            @RequestParam(defaultValue = "10") Integer limit) {
        log.info("查询最近的变更记录，limit: {}", limit);
        
        QueryWrapper<SalesOutChangeRecord> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("operate_time");
        wrapper.last("LIMIT " + limit);
        
        List<SalesOutChangeRecord> records = changeRecordService.list(wrapper);
        
        return R.data(records);
    }

    /**
     * 按操作类型统计
     *
     * @return 各操作类型的统计数据
     */
    @GetMapping("/statistics/byOperationType")
    @ApiOperation(value = "按操作类型统计", notes = "统计各操作类型（SAVE/SUBMIT/UPDATE/DELETE）的变更次数")
    public R statisticsByOperationType() {
        log.info("按操作类型统计变更记录");
        
        // 统计各操作类型
        QueryWrapper<SalesOutChangeRecord> saveWrapper = new QueryWrapper<>();
        saveWrapper.eq("operation_type", "SAVE");
        long saveCount = changeRecordService.count(saveWrapper);
        
        QueryWrapper<SalesOutChangeRecord> submitWrapper = new QueryWrapper<>();
        submitWrapper.eq("operation_type", "SUBMIT");
        long submitCount = changeRecordService.count(submitWrapper);
        
        QueryWrapper<SalesOutChangeRecord> updateWrapper = new QueryWrapper<>();
        updateWrapper.eq("operation_type", "UPDATE");
        long updateCount = changeRecordService.count(updateWrapper);
        
        QueryWrapper<SalesOutChangeRecord> deleteWrapper = new QueryWrapper<>();
        deleteWrapper.eq("operation_type", "DELETE");
        long deleteCount = changeRecordService.count(deleteWrapper);
        
        // 构建返回结果
        return R.data(new java.util.HashMap<String, Object>() {{
            put("saveCount", saveCount);
            put("submitCount", submitCount);
            put("updateCount", updateCount);
            put("deleteCount", deleteCount);
            put("totalCount", saveCount + submitCount + updateCount + deleteCount);
        }});
    }

    /**
     * 按变更类型统计
     *
     * @return 各变更类型的统计数据
     */
    @GetMapping("/statistics/byChangeType")
    @ApiOperation(value = "按变更类型统计", notes = "统计商品明细和费用的变更次数")
    public R statisticsByChangeType() {
        log.info("按变更类型统计变更记录");
        
        // 统计商品明细变更
        QueryWrapper<SalesOutChangeRecord> commodityWrapper = new QueryWrapper<>();
        commodityWrapper.eq("change_type", "COMMODITY");
        long commodityCount = changeRecordService.count(commodityWrapper);
        
        // 统计费用变更
        QueryWrapper<SalesOutChangeRecord> costWrapper = new QueryWrapper<>();
        costWrapper.eq("change_type", "COST");
        long costCount = changeRecordService.count(costWrapper);
        
        // 统计综合变更
        QueryWrapper<SalesOutChangeRecord> combinedWrapper = new QueryWrapper<>();
        combinedWrapper.eq("change_type", "COMBINED");
        long combinedCount = changeRecordService.count(combinedWrapper);
        
        // 构建返回结果
        return R.data(new java.util.HashMap<String, Object>() {{
            put("commodityCount", commodityCount);
            put("costCount", costCount);
            put("combinedCount", combinedCount);
            put("totalCount", commodityCount + costCount + combinedCount);
        }});
    }
}
